package com.zzzzzz.account;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.zzzzzz.account.model.EmailSend;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service
public class MailService {

	private static final String DEFAULT_ENCODING = "utf-8";

	private static Logger logger = LoggerFactory.getLogger(MailService.class);

	@Resource
	private JavaMailSender mailSender;
	@Resource
	private FreeMarkerConfigurationFactoryBean freeMarkerConfigurationFactoryBean;

	/**
	 * 发送MIME格式的用户修改通知邮件.
	 */
	public void sendMail(EmailSend emailSend) {

		try {
			MimeMessage msg = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);

			helper.setTo(emailSend.getSendTo());
			helper.setFrom(emailSend.getSendFrom());
			helper.setSubject(emailSend.getSubject());

			String content = this.generateContent(emailSend.getHtmlTemplate(),emailSend.getHtmlData());
			helper.setText(content, true);

			mailSender.send(msg);
			logger.info("HTML版邮件已发送");
		} catch (MessagingException e) {
			logger.error("构造邮件失败", e);
		} catch (Exception e) {
			logger.error("发送邮件失败", e);
		}
	}

	/**
	 * 使用Freemarker生成html格式内容.
	 */
	@SuppressWarnings("unchecked")
	private String generateContent(String htmlTemplate,Map<String,Object> htmlData) throws MessagingException {
		try {
			Template template = freeMarkerConfigurationFactoryBean.createConfiguration().getTemplate(htmlTemplate, DEFAULT_ENCODING);
			return FreeMarkerTemplateUtils.processTemplateIntoString(template, htmlData);
		} catch (IOException e) {
			logger.error("生成邮件内容失败, FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}

}
